import React, { ReactNode, useEffect, useState } from "react";
import { QueryClient, QueryClientProvider } from "react-query";
import { User } from "types/user";
import { getToken, http } from "utils/http";

const bootstrapUser = async () => {
  const data = await http("info", { token: getToken() });
  return data;
};

const AuthContext = React.createContext<
  | {
      user: User | null;
      logout: () => Promise<void>;
      login: (user: User) => void;
    }
  | undefined
>(undefined);
AuthContext.displayName = "AuthContext";

export const localStorageTokenKey = "__auth_token__";
const logouts = async () =>
  window.localStorage.removeItem(localStorageTokenKey);

export const AuthProvide = ({ children }: { children: ReactNode }) => {
  const [user, setUser] = useState<User | null>(null);
  const login = (user: User) => {
    setUser(user);
  };
  const logout = () =>
    logouts().then(() => {
      setUser(null);
    });

  useEffect(() => {
    bootstrapUser().then((res) => {
      if (res) {
        setUser(res);
      }
    });
  }, []);
  return (
    <QueryClientProvider client={new QueryClient()}>
      <AuthContext.Provider
        children={children}
        value={{ user, logout, login }}
      />
    </QueryClientProvider>
  );
};

export const useAuth = () => {
  const context = React.useContext(AuthContext);
  if (!context) {
    throw new Error("useAuth必须在AuthProvider中使用");
  }
  return context;
};
